package com.yuanheng100.ems4j.service;

import com.alibaba.fastjson.JSON;
import com.yuanheng100.ems4j.api.IDepartmentService;
import com.yuanheng100.ems4j.mapper.Ems4jDepartmentMapper;
import com.yuanheng100.ems4j.model.Ems4jDepartment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by jlqian on 2017/1/11.
 */
@Service
public class DepartmentServiceImpl implements IDepartmentService
{
    private static Logger logger = LoggerFactory.getLogger(DepartmentServiceImpl.class);

    @Autowired
    private Ems4jDepartmentMapper ems4jDepartmentMapper;

    @Override
    public Ems4jDepartment getDepartmentById(int depId)
    {
        Ems4jDepartment ems4jDepartment = ems4jDepartmentMapper.selectByPrimaryKey(depId);
        return ems4jDepartment;
    }

    @Override
    public List<Ems4jDepartment> getSubDepartmentsByParentId(int parentId, int layer, short depType, int appId)
    {
        Long before = null;
        Long after = null;

        before = System.currentTimeMillis();
        //取得当前层
        Ems4jDepartment parnetDepartment = ems4jDepartmentMapper.selectByPrimaryKey(parentId);
        if (parnetDepartment == null)
        {
            return null;
        }
        if (layer == 0)
        {
            layer = Integer.MAX_VALUE;
        }
        //第一层到规定层数
        getSubDepartmentsByParentIdAndDeptype(parentId, depType, appId, layer, 0, parnetDepartment);
        after = System.currentTimeMillis();
        logger.info("获取部门操作耗费时间为：{}ms", after - before);
        return parnetDepartment.getSubDepartmentList();
    }

    /**
     * 获取当前部门下的子部门
     *
     * @param parentId
     * @param deptype
     * @param layer
     * @param currentLayer
     * @param parnetDepartment
     */
    private void getSubDepartmentsByParentIdAndDeptype(int parentId, short deptype, int appId, int layer, int currentLayer, Ems4jDepartment parnetDepartment)
    {

        List<Ems4jDepartment> subEms4jDepartments = ems4jDepartmentMapper.selectByParentid(parentId);
        parnetDepartment.setSubDepartmentList(subEms4jDepartments);
        currentLayer++;
        if (currentLayer < layer && !subEms4jDepartments.isEmpty())
        {
            for (Ems4jDepartment ms4jDepartment : subEms4jDepartments)
            {
                getSubDepartmentsByParentIdAndDeptype(ms4jDepartment.getId(), deptype, appId, layer, currentLayer, ms4jDepartment);
            }
        } else if (!subEms4jDepartments.isEmpty())
        {
            removeDepartmentsNotDeptypeAndAppId(subEms4jDepartments, deptype, appId);
        }
    }


    /**
     * 删除不符合部门类型和应用ID的部门
     *
     * @param ems4jDepartments
     * @param deptype
     * @param appId
     */
    private void removeDepartmentsNotDeptypeAndAppId(List<Ems4jDepartment> ems4jDepartments, short deptype, int appId)
    {
        for (Ems4jDepartment ems4jDepartment : ems4jDepartments)
        {
            if (deptype != 0 && deptype != ems4jDepartment.getDeptype())
            {
                ems4jDepartments.remove(ems4jDepartment);
            }
            if (appId != 0)
            {
                String appids = ems4jDepartment.getAppids();
                List<Integer> list = JSON.parseArray(appids, Integer.class);
                if (list == null || !list.contains(appId))
                {
                    ems4jDepartments.remove(ems4jDepartment);
                }
            }
        }
    }

    @Override
    public Ems4jDepartment getParentDepartment(int depId, int layer, int appId)
    {
        if (layer == 0)
        {
            layer = Integer.MAX_VALUE;
        }
        Ems4jDepartment ems4jDepartment = ems4jDepartmentMapper.selectParentByPrimaryKey(depId);
        if (layer > 1)
        {
            getRecursionParentDepartment(ems4jDepartment, layer, 1);
        }
        return ems4jDepartment;
    }

    /**
     * 递归查询父部门
     *
     * @param ems4jDepartment
     * @param layer
     * @param curremtLayer
     */
    private void getRecursionParentDepartment(Ems4jDepartment ems4jDepartment, int layer, int curremtLayer)
    {
        if (ems4jDepartment == null)
        {
            return;
        }
        Ems4jDepartment parent = ems4jDepartmentMapper.selectParentByPrimaryKey(ems4jDepartment.getId());
        if (ems4jDepartment.getId().equals(parent.getId()) || parent == null)
        {
            return;
        }
        ems4jDepartment.setParentDepartment(parent);
        curremtLayer++;
        if (curremtLayer < layer)
        {
            getRecursionParentDepartment(parent, layer, curremtLayer);
        }
    }

    @Override
    public int isParent(int parentDepId, int subDepId, int appId)
    {
        Ems4jDepartment ems4jDepartment = ems4jDepartmentMapper.selectByPrimaryKey(subDepId);
        Ems4jDepartment parEms4jDepartment1 = ems4jDepartmentMapper.selectByPrimaryKey(parentDepId);
        if (ems4jDepartment == null || parEms4jDepartment1 == null)
        {
            return -1;
        }
        if (ems4jDepartment.getParentid() == null)
        {
            if (parEms4jDepartment1.getParentid() == null)
            {
                return 0;
            } else
            {
                return -1;
            }
        }
        if (ems4jDepartment.getParentid().equals(parentDepId))
        {
            return 1;
        } else
        {
            List<Ems4jDepartment> ems4jDepartments = ems4jDepartmentMapper.selectByParentid(ems4jDepartment.getParentid());
            for (Ems4jDepartment department : ems4jDepartments)
            {
                if (department.getId().equals(parentDepId))
                {
                    return 0;
                }
            }
        }
        int relation = 2;
        Ems4jDepartment currentEms4jDepartment = ems4jDepartment;
        for (; ; )
        {
            Ems4jDepartment parent = ems4jDepartmentMapper.selectByPrimaryKey(currentEms4jDepartment.getParentid());
            if (parent != null && parent.getId().equals(parentDepId))
            {
                return relation;
            } else if (parent == null || parent.getId().equals(currentEms4jDepartment.getId()))
            {
                break;
            } else
            {
                relation++;
                currentEms4jDepartment = parent;
            }
        }
        return -1;
    }

    @Override
    public Ems4jDepartment getRootDepartment(int appId)
    {
        List<Ems4jDepartment> ems4jDepartments = ems4jDepartmentMapper.selectRootDepartment();
        for (Ems4jDepartment ems4jDepartment : ems4jDepartments)
        {
            String appids = ems4jDepartment.getAppids();
            List<Integer> list = JSON.parseArray(appids, Integer.class);
            if (list != null && list.contains(appId))
            {
                return ems4jDepartment;
            }
        }
        return null;
    }

    @Override
    public int addDepartment(Ems4jDepartment department)
    {
        department.setCreatetime(new Date());
        logger.info("新增部门：" + JSON.toJSONString(department));
        int insert = ems4jDepartmentMapper.insert(department);
        return insert >= 0 ? department.getId() : insert;
    }

    @Override
    public int updateDepartment(Ems4jDepartment department)
    {
        logger.info("修改部门：" + JSON.toJSONString(department));
        return ems4jDepartmentMapper.updateByPrimaryKey(department);
    }

    @Override
    public List<Ems4jDepartment> getAllDepartments()
    {
        return ems4jDepartmentMapper.selectAllDepartments();
    }

    @Override
    public int transferSubDepartment(Integer fromDepartmentId, Integer toDepartmentId)
    {
        return ems4jDepartmentMapper.transferSubDepartment(fromDepartmentId, toDepartmentId);
    }

}
